package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.execption.MyException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class MyLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(myLogin)")
    public Object login(ProceedingJoinPoint joinPoint, MyLogin myLogin) throws Throwable {
        //springmvc 获取request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        //获取token
        String token = request.getHeader("token");

        //判断是否必须要进行登录校验default required = false
        if (myLogin.required()) {
            //redis中通过token获取用户信息
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
            //如果用户信息为空（登录过期），或者token为空
            if (userInfo == null || StringUtils.isEmpty(token)) {
                //跳转登录页面
                throw new MyException(ResultCodeEnum.LOGIN_AUTH);
            }
        }

        //过滤不必要登录，先判断token是否为空
        //查看是否登录
        if (!StringUtils.isEmpty(token)) {
            //通过token获取用户信息
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
            if (userInfo != null) {
                //获取userid放到threadLocal中
                AuthContextHolder.setUserId(userInfo.getId());
            }
        }

        return joinPoint.proceed();
    }
}
